<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-container class="mydept">
      <el-aside width="180px">
        <el-tree
          :data="deptsTree"
          :props="defaultProps"
          accordion
          @node-click="handleNodeClick"
        >
        </el-tree>
      </el-aside>
      <el-main>
        <el-card>
          <el-form :inline="true" :model="searchVo" class="demo-form-inline">
            <el-form-item label="条件查询:">
              <el-input
                v-model="searchVo.condition"
                placeholder="账号/姓名/手机号"
              ></el-input>
            </el-form-item>
            <el-form-item label="开始时间:">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="searchVo.startTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间:">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="searchVo.endTime"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSubmit"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-circle-plus"
                v-has="'/system/user/add'"
                @click="openAddDialog"
                >添加</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button  v-has="'/system/user/add'" type="primary" icon="el-icon-folder">导出</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="depts" border style="width: 100%">
            <el-table-column type="selection" width="55px"> </el-table-column>
            <el-table-column prop="account" label="账号"> </el-table-column>
            <el-table-column prop="name" label="姓名"> </el-table-column>
            <el-table-column prop="simpleName" label="部门名">
            </el-table-column>
            <el-table-column prop="posName" label="职位"> </el-table-column>
            <el-table-column prop="phone" label="电话"> </el-table-column>
            <el-table-column prop="phone" label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-value="ENABLE"
                  inactive-value="DISABLE"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="changeSwitch(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="210px">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <el-button
                  @click="deleteClick(scope.row)"
                  type="text"
                  size="small"
                  v-has="'/system/user/deleteUser'"
                  >删除</el-button
                >
                <el-button
                  @click="openEditDialog(scope.row)"
                  type="text"
                  size="small"
                  v-has="'/system/user/update'"
                  >编辑</el-button
                >
                <el-button
                  @click="fenRole(scope.row)"
                  type="text"
                  size="small"
                  v-has="'/mgr/setRole'"
                  >分配角色</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentpage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-card>
        <!--用户添加弹出框-->
        <el-dialog
          title="用户添加"
          :visible.sync="dialogFormVisible"
          width="60%"
          :before-close="handleClose"
        >
          <el-form label-width="100px" :model="user" :rules="rules" ref="userForm">
            <el-card>
              <div slot="header" class="clearfix">
                <span>基础信息</span>
              </div>
              <el-form-item label="账号:" prop="account">
                <el-input v-model="user.account"></el-input>
              </el-form-item>
              <el-form-item label="姓名:" prop="name">
                <el-input v-model="user.name"></el-input>
              </el-form-item>
              <el-form-item label="出生日期:">
                <el-date-picker
                  type="date"
                  placeholder="出生日期"
                  v-model="user.birthday"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="密码:" prop="password">
                    <el-input v-model="user.password"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="确认密码:" prop="confirmpassword">
                    <el-input v-model="user.confirmpassword"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="邮箱:" prop="email">
                <el-input v-model="user.email"></el-input>
              </el-form-item>
              <el-form-item label="性别:" prop="sex">
                <el-radio-group v-model="user.sex">
                  <el-radio label="M">男</el-radio>
                  <el-radio label="F">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="电话:" prop="phone">
                <el-input v-model="user.phone"></el-input>
              </el-form-item>
            </el-card>

            <el-card class="deptInfo">
                <div slot="header" class="clearfix">
                <span>部门信息</span>
              </div>
                     <el-form-item label="部门">
                            <el-input
                                placeholder="请选择上级名称"
                                class="width-220 selectTree-input"
                                auto-complete="off"
                                v-model="user.pname"
                                @click.native="changeSelectTree()"
                                @blur="hideParentClick"
                            >
                            </el-input>
                            <el-tree
                                id="floatTree"
                                v-show="isShowSelect"
                                empty-text="暂无数据"
                                :highlight-current="true"
                                :default-expand-all="false"
                                :expand-on-click-node="true"
                                :data="deptsTree"
                                :filter-node-method="filterNode"
                                @node-click="selectClassfy"
                                class="width-220 selectTree-input objectTree"
                                ref="selectTree"
                                :props="defaultProps"
                            >
                            </el-tree>
                    </el-form-item>
                 </el-col>
                <el-form-item label="职位">
                    <el-select v-model="user.positionId" placeholder="请选择职位">
                    <el-option v-for="item in allPosition" :label="item.name" :value="item.positionId" :key="item.postionId"></el-option>
                    </el-select>
                </el-form-item>
             
            
            </el-card>
            <el-form-item>
              <el-button type="primary" @click="submitDeptForm('userForm')"
                >提交</el-button
              >
              <el-button @click="resetDeptForm('userForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>


        <!--用户修改弹出框-->
       <el-dialog
          title="用户修改"
          :visible.sync="editdialogFormVisible"
          width="60%"
          :before-close="handleClose"
        >
          <el-form label-width="100px" :model="user" :rules="rules" ref="userForm">
            <el-card>
              <div slot="header" class="clearfix">
                <span>基础信息</span>
              </div>
              <el-form-item label="姓名:" prop="name">
                <el-input v-model="user.name"></el-input>
              </el-form-item>
              <el-form-item label="出生日期:">
                <el-date-picker
                  type="date"
                  placeholder="出生日期"
                  v-model="user.birthday"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="邮箱:" prop="email">
                <el-input v-model="user.email"></el-input>
              </el-form-item>
              <el-form-item label="性别:" prop="sex">
                <el-radio-group v-model="user.sex">
                  <el-radio label="M">男</el-radio>
                  <el-radio label="F">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="电话:" prop="phone">
                <el-input v-model="user.phone"></el-input>
              </el-form-item>
            </el-card>
            <el-card class="deptInfo">
                <div slot="header" class="clearfix">
                <span>部门信息</span>
              </div>
                     <el-form-item label="部门">
                            <el-input
                                placeholder="请选择上级名称"
                                class="width-220 selectTree-input"
                                auto-complete="off"
                                v-model="user.pname"
                                @click.native="changeSelectTree()"
                                @blur="hideParentClick"
                            >
                            </el-input>
                            <el-tree
                                id="floatTree"
                                v-show="isShowSelect"
                                empty-text="暂无数据"
                                :highlight-current="true"
                                :default-expand-all="false"
                                :expand-on-click-node="true"
                                :data="deptsTree"
                                :filter-node-method="filterNode"
                                @node-click="selectClassfy"
                                class="width-220 selectTree-input objectTree"
                                ref="selectTree"
                                :props="defaultProps"
                            >
                            </el-tree>
                    </el-form-item>
                 </el-col>
                <el-form-item label="职位">
                    <el-select v-model="user.positionId" placeholder="请选择职位">
                    <el-option v-for="item in allPosition" :label="item.name" :value="item.positionId" :key="item.postionId"></el-option>
                    </el-select>
                </el-form-item>
             
            
            </el-card>
            <el-form-item>
              <el-button type="primary" @click="submitDeptForm('userForm')"
                >提交</el-button
              >
              <el-button @click="resetDeptForm('userForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <!--分配角色弹出框-->
        <el-dialog
          :title="roleTitle"
          :visible.sync="roledialogFormVisible"
          width="40%"
          :before-close="handleClose"
        >
                 <el-checkbox-group v-model="userRoles">
                      <el-checkbox v-for="role in roles" :label="role.roleId"  :key="role.roleId">{{role.name}}</el-checkbox>
                </el-checkbox-group>
                <div style="margin-top:20px;"></div>
                   <el-button type="primary" @click="confirmUserRole">确认</el-button>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roledialogFormVisible:false,
      isShowSelect: false, //控制树形结构是否显示
      dialogFormVisible: false, //控制弹出框显示和隐藏
      currentpage: 1, //标识当前页码
      pagesize: 5, //每页显示的条数
      total: 0, //总条数
      deptsTree: [], //存储部门的树形结构
      extendNode: [], //默认展开的树形节点
      depts: [], //查询所有部门的信息
      roles:[],
      userRoles:[],
      roleIds:[],
      roleTitle:"",
      roleUserId:0,
      editdialogFormVisible:false,
      defaultProps: {
        children: "children",
        label: "fullName",
      },
      searchVo: {},
      user: { sex: "M" },
      allPosition:[],
      rules: {
        simpleName: [
          { required: true, message: "请输入部门名称", trigger: "blur" },
        ],

        fullName: [
          { required: true, message: "请输入部门全称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.initDeptTree();
    this.onSubmit();
  },
  methods: {
    //确认分配角色
   async confirmUserRole(){
       let result= await this.$http.post("/system/user/fenUserRole?userId="+this.roleUserId+"&roleIds="+this.userRoles);
       if(result.data.code==20000){
             this.$message.success("角色分配成功");
             this.roledialogFormVisible=false;
       }
    },
   //打开分配角色的弹出框
   async fenRole(row){
        let result = await this.$http.get("/system/role/findAll/"+row.userId);
        if(result.data.code===20000){
            this.roles=result.data.data.roles;
            this.userRoles=result.data.data.userRoles;
            this.roleTitle="分配["+row.account+"]角色";
            this.roleUserId=row.userId;
            this.roledialogFormVisible=true;
        }
   },

    //打开添加用户的窗口
   async openAddDialog(){
         this.dialogFormVisible=true;
         let result=await this.$http.get("/system/position/getAllPosition");
         this.allPosition=result.data.data.allPosition;
    },
    //修改状态
    async changeSwitch(row) {
      let userId = row.userId;
      let status = row.status;
      let result = await this.$http.post(
        "/system/user/updateStatus?userId=" + userId + "&status=" + status
      );
      if (result.data.code === 20000) {
        this.$message.success("修改状态成功");
        this.onSubmit();
      }
    },
    //每页大小发生改变时触发
    handleSizeChange(val) {
      this.pagesize = val;
      this.onSubmit();
    },
    handleCurrentChange(val) {
      this.currentpage = val;
      this.onSubmit();
    },
    //删除市场部
    deleteClick(row) {
      this.$confirm("是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await this.$http.post(
            "/system/user/deleteUser/" + row.userId
          );
          if ((result.data.code = 20000)) {
            this.$message.success(result.data.message);
          }
          this.initDeptTree();
          this.onSubmit();
        })
        .catch(() => {
          //几点取消的提示
        });
    },
    async openEditDialog(row) {
      let result = await this.$http.get("/system/user/findById/" + row.userId);
      if (result.data.code === 20000) {
        this.editdialogFormVisible = true;
        this.user = result.data.data.userPos;
        this.allPosition=result.data.data.allPosition;
      }
    },
    //关闭弹出框
    handleClose(done) {
      this.user = {};
      this.dialogFormVisible = false;
      this.editdialogFormVisible=false;
      this.roledialogFormVisible=false;
      this.roles=[];
      this.userRoles=[];
      this.roleTitle="";
      this.roleUserId=0;
    },
    submitDeptForm(userForm) {
      if (this.user.userId) {
        this.updateUserForm(userForm);
      } else {
        this.addUserForm(userForm);
      }
    },
    //添加部门
    async addUserForm(userForm) {
      //  this.$refs[userForm].validate(async valid => {
      //       if (valid) {
      let result = await this.$http.post("/system/user/addUser", this.user);
      if (result.data.code === 20000) {
        this.$message.success(result.data.message);
      }
      this.dialogFormVisible = false;
      this.initDeptTree();
      this.onSubmit();
      // }else{
      //     return false;
      // }
      //  })
    },
    //修改部门
    async updateUserForm(userForm) {
      //  this.$refs[userForm].validate(async valid => {
      //       if (valid) {
      let result = await this.$http.post("/system/user/updateUser", this.user);
      if (result.data.code === 20000) {
        this.$message.success(result.data.message);
      }
      this.editdialogFormVisible = false;
      this.initDeptTree();
      this.onSubmit();
      // }else{
      //     return false;
      // }
      //  })
    },
    //搜索查询
    async onSubmit() {
      let result = await this.$http.post(
        "/system/user/selectByPageCon/" +
          this.currentpage +
          "/" +
          this.pagesize,
        this.searchVo
      );
      if (result.data.code === 20000) {
        this.depts = result.data.data.records;

        this.total = parseInt(result.data.data.total);
      }
    },
    //初始化部门树形结构
    async initDeptTree() {
      let result = await this.$http.get("/system/dept/findDeptTree");
      if (result.data.code === 20000) {
        this.deptsTree = result.data.data.deptTree;
        console.log(this.deptsTree);
      }
    },
    stateFormatter(row, column, cellValue, index) {
      //显示员工状态是否在职
      return cellValue == "1" ? "展开" : "未展开";
    },
    handleNodeClick(data) {
      this.searchVo.deptId = data.deptId;
      this.onSubmit();
    },
    selectClassfy(data) {
      this.user.pname = data.fullName;
      this.user.deptId = data.deptId;
      this.isShowSelect = false;
    },
    changeSelectTree() {
      this.isShowSelect = true;
    },
    hideParentClick(e) {
      var isOther =
        e.relatedTarget == null ||
        e.relatedTarget.closest("div.el-tree") == null ||
        e.relatedTarget.closest("div.el-tree").id != "floatTree";

      if (isOther) {
        this.isShowSelect = false;
      } else {
        e.target.focus();
      }
    },
    // 选择器的树节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },
};
</script>
<style scoped>
.el-main .el-container .el-aside {
  margin-top: 20px;
  height: 100%;
}
/*下拉框选择树*/
.objectTree {
  position: absolute;
  overflow: auto;
  z-index: 100;
  height: 200px;
  border: 1px solid #ddd;
  line-height: normal;
  z-index: 204;
}
.width-220 {
  width: 220px;
}
.deptInfo {
  margin-top: 10px;
  margin-bottom: 20px;
}
</style>